# -*- encoding:utf8 -*-
from __future__ import unicode_literals
from django.conf import settings
import requests
import json

class PTS(object):
    def __init__(self):
        self.url=settings.PTS_DOMAIN+'/cmd/'
    
    def request(self,dc):
        try:
            rt = requests.post(self.url,json.dumps(dc))
        except Exception as e:
            raise UserWarning,'connect to pts has error, may be pts not online' 
        if rt.status_code!=200:
            print(rt.text)
            raise UserWarning,'PTS return code :{code} '.format(code=rt.status_code)
        rt = json.loads(rt.text)
        if rt.get('msg'):
            raise UserWarning,rt.get('msg')
        else:
            return rt

            
    def get_studios(self):
        """
        rt:  studio name list : [ name1,name2]
        """
        dc={'get_studios':{}}
        rt = self.request(dc)
        studios = rt.get('get_studios')
        return studios
    
    def get_apps(self,studio):
        """
        @studio:str: studio name (in pts is pub_name)
        
        rt:
            app list : [{}]
        """
        dc={
            'get_apps':{'studio':studio}
        }
        rt = self.request(dc)
        return rt.get('get_apps')
    
    def get_app_info(self,sku):
        dc={
            'get_app_info':{'sku':sku}
        }
        rt = self.request(dc)
        return rt.get('get_app_info')
    
    def update_apps_info(self,skus):
        """
        从pts系统批量获取：'sku':app.prd_id,
            'app_code':app.prj_code,
            'pub_name':app.appextrainfo.pub_name,
            'media_url'
        """
        dc={
            'get_apps_info':{'skus':skus}
        }
        rt = self.request(dc)
        return rt.get('get_apps_info')